import { VuexModule, Module, Mutation, Action } from "vuex-module-decorators";
import { LocalStorage as LocalEnum } from "@/utils/VEnum";
import { user_login } from "@/api/user";

interface IUserState {
  _isAdmin: boolean;
}

interface IUser {
  name?: string;
  account?: string;
  email?: string;
  isAdmin?: boolean;
}

@Module({ name: "User" })
export default class User extends VuexModule implements IUserState {
  _isAdmin: boolean = false;

  _user: IUser = {};

  _spinning: boolean = true;

  get spinning() {
    return this._spinning;
  }

  get isAdmin() {
    return this._isAdmin;
  }

  get token() {
    return localStorage.getItem(LocalEnum.TOKEN.toString()) || "";
  }

  get user() {
    // return this._user;
    const userStr = localStorage.getItem(LocalEnum.USER.toString());
    return userStr ? JSON.parse(userStr) : {};
  }

  @Mutation
  private LOADING(loading: boolean) {
    this._spinning = loading;
  }

  @Mutation
  private UPDATE_IS_ADMIN(admin: boolean) {
    this._isAdmin = admin;
  }

  @Mutation
  private UPDATE_USER(user: IUser) {
    // this._user = user;
    localStorage.setItem(LocalEnum.USER.toString(), JSON.stringify(user));
  }

  @Mutation
  private UPDATE_TOKEN(token: string) {
    // console.log("update-token", token);
    if (token) {
      localStorage.setItem(LocalEnum.TOKEN.toString(), token);
    } else {
      localStorage.clear();
    }
  }

  @Action({ commit: "LOADING" })
  public async loading(load: boolean) {
    return load;
  }

  @Action({ commit: "UPDATE_IS_ADMIN" })
  public async setIsAdmin(admin: boolean) {
    return admin;
  }

  @Action({ commit: "UPDATE_TOKEN" })
  public async userLogin(form: any) {
    try {
      this.LOADING(false); // loading
      const { data } = await user_login(form);
      if (data.errNo === 0) {
        const { email, account, isAdmin } = data?.item?.user;
        this.UPDATE_USER({ name: account, email, account });
        return "token";
      }
      return "token";
    } catch (error) {
      this.LOADING(true);
      return "";
    }
  }

  /**
   * @deprecated 未对接
   */
  @Action({ commit: "UPDATE_USER" })
  public async getUserInfo() {
    return { name: "reload" };
  }

  @Action({ commit: "UPDATE_TOKEN" })
  public async resetToken() {
    return "";
  }

  @Action({ commit: "UPDATE_TOKEN" })
  public async logout(e: any) {
    // console.log("前端登出");
    return "";
  }
}
